import React, { useState, useCallback, useRef, useEffect } from 'react';
import { Popup } from 'antd-mobile';
import SkuComponent from '@/components/sku/sku';
import { useAppSelector, useAppDispatch } from '@/store';
import {
    updateSkuChooseVisible, updateSelectedSku
} from '@/store/reducers/skuReducers';
import Loadding from '@/components/loadding';
import { GoodsBuyType } from '../context';


export interface SkuModelProps {
    goodsInfo?: any;
    handlerBuy?: (value: GoodsBuyType) => void;
}

const SkuModel: React.FC<SkuModelProps> = (props) => {
    const { goodsInfo, handlerBuy } =
    {
        ...props
    };

    const skuChooseVisible = useAppSelector(state => state.sku.skuChooseVisible);
    const dispatch = useAppDispatch();
    const [isLoading, setIsLoading] = useState<boolean>(false);

    const timer = useRef<any>();

    const cancel = useCallback(() => {
        if (timer.current) {
            clearTimeout(timer.current);
            timer.current = null;
        }
    }, []);

    const onConfirm = (selectedSku: any) => {
        handlerBuy?.(selectedSku);
    }

    const onUpdateSelectedSku = (selectedSku: any) => {
        if (!selectedSku) {
            return;
        }
        if (isLoading) {
            return;
        }
        setIsLoading(true);
        dispatch(updateSelectedSku(selectedSku));

        timer.current = setTimeout(() => {
            setIsLoading(false);
        }, 800);
    }

    useEffect(() => {

        return () => {
            cancel();
        };
    }, []);


    const closeModel = () => {
        dispatch(updateSkuChooseVisible(false));
    }

    return (
        <Popup
            visible={skuChooseVisible}
            showCloseButton
            bodyStyle={{ height: '75%', padding: '18px' }}
            forceRender
            closeOnSwipe
            onClose={() => {
                closeModel()
            }}
            onMaskClick={() => {
                closeModel()
            }}
        >
            <SkuComponent
                goods={goodsInfo}
                onConfirm={onConfirm}
                onUpdateSelectedSku={onUpdateSelectedSku}
            />

            <Loadding visible={isLoading} />
        </Popup>
    )
}

export default SkuModel;